package com.atguigu.champter8;

import com.atguigu.beans.HotItem;
import com.atguigu.beans.UserBehavior;
import com.atguigu.utils.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Comparator;
import java.util.List;


//每隔5分钟输出最近一小时内点击量最多的3件商品
public class Flink03_Project_High_TopN {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 9999);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        env
                .readTextFile("datas/input/UserBehavior.csv")
                .map(line -> {
                    String[] data = line.split(",");
                    return new UserBehavior(Long.valueOf(data[0]), Long.valueOf(data[1]), Integer.valueOf(data[2]), data[3], Long.parseLong(data[4]) * 1000);
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner((event, timestamp) -> event.getTimestamp())
                )
                .keyBy(UserBehavior::getItemId)
                .window(SlidingEventTimeWindows.of(Time.hours(3), Time.minutes(60)))
                .aggregate(new AggregateFunction<UserBehavior, Long, Long>() {
                               @Override
                               public Long createAccumulator() {
                                   return 0L;
                               }

                               @Override
                               public Long add(UserBehavior value, Long acc) {
                                   return ++acc;
                               }

                               @Override
                               public Long getResult(Long acc) {
                                   return acc;
                               }

                               @Override
                               public Long merge(Long a, Long b) {
                                   return a + b;
                               }
                           },
                        new ProcessWindowFunction<Long, HotItem, Long, TimeWindow>() {
                            @Override
                            public void process(Long key,
                                                Context ctx,
                                                Iterable<Long> elements,
                                                Collector<HotItem> out) throws Exception {
                                long end = ctx.window().getEnd();
                                out.collect(new HotItem(key,elements.iterator().next(),end));
                            }
                        })
                //求点击量的top3
                //同一个窗口的进行比较
                .keyBy(HotItem::getWindowEndTime)
                .process(new KeyedProcessFunction<Long, HotItem, String>() {

                    private ListState<HotItem> top3;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        top3 = getRuntimeContext().getListState(new ListStateDescriptor<HotItem>("top3", HotItem.class));
                    }

                    @Override
                    public void processElement(HotItem value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {

                        // 当属于某个窗口的第一个元素过来, 需要注册定时器
                        //ENDTIME是窗口的endtime,数据以窗口为单位发送过来
                       if (!top3.get().iterator().hasNext()){
                           ctx.timerService().registerEventTimeTimer(value.getWindowEndTime() + 5000);
                       }
                       top3.add(value);
                    }

                    @Override
                    public void onTimer(long timestamp,
                                        OnTimerContext ctx,
                                        Collector<String> out) throws Exception {
                        List<HotItem> items = AtguiguUtil.toList(top3.get());
                        items.sort(new Comparator<HotItem>() {
                            @Override
                            public int compare(HotItem o1, HotItem o2) {
                                return -o1.getCount().compareTo(o2.getCount());
                            }
                        });
                        //状态中存储了所有的数据
                        /*if (items.size() == 4) {
                            items.remove(3);
                        }

                        out.collect("最热Top3 :"+items.toString());*/

                        String msg = "------------\n";
                        for (int i = 0; i < Math.min(3, items.size()); i++) {
                            msg += items.get(i) +"----"+ items.size() +"\n";
                        }

                        out.collect(msg);

                    }
                })
                .print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
